import 'dart:io';

import 'package:gate_cli/utils/intl_view/utils/intl_arb_file.dart';
import 'package:gate_cli/utils/intl_view/utils/pull_smartling_flutter.dart';
import 'package:path/path.dart';

class SmartlingIntl {
  static SmartlingIntl instance = SmartlingIntl();

  IntlArbFile getArb(String name) {
    final path = join(
      getSmartlingDirectory().path,
      'I10n',
      '$name.arb',
    );
    return IntlArbFile(path: path, locale: 'en');
  }

  /// 获取 smartling_flutter 项目中的 arb 文件列表
  List<String> getArbNames() {
    final smartlingFlutterDirectory = getSmartlingDirectory();
    final files = Directory(join(smartlingFlutterDirectory.path, 'I10n'))
        .listSync()
        .map((e) => e.path)
        .where((element) => element.endsWith('.arb'))
        .map((e) => basename(e))
        .toList();
    return files;
  }

  List<IntlArbFile> getTranslatedArbs(String name) {
    final path = join(
      getSmartlingDirectory().path,
      'translated',
      name,
    );
    final directory = Directory(path);
    if (!directory.existsSync()) {
      return [];
    }
    return directory
        .listSync()
        .map((e) => e.path)
        .where((element) => element.endsWith('.arb'))
        .map((e) => IntlArbFile(path: e, locale: getLocale(e, name)))
        .toList();
  }

  String getLocale(String path, String name) {
    final locale = basenameWithoutExtension(path).replaceAll('${name}_', '');
    if (locale == 'zh') {
      return 'zh_Hans';
    } else {
      return locale;
    }
  }
}
